﻿namespace IPMS.Sort
{
    using System;
    using System.Collections;
    using System.Web.UI.WebControls;

    public class IPSortList
    {
        public static void SortByText(ListControl combo)
        {
            SortCombo(combo, new ComboTextComparer());
        }

        public static void SortByValue(ListControl combo)
        {
            SortCombo(combo, new ComboValueComparer());
        }

        private static void SortCombo(ListControl combo, IComparer comparer)
        {
            if (combo.Items.Count > 1)
            {
                int i;
                ArrayList arrItems = new ArrayList();
                for (i = 0; i < combo.Items.Count; i++)
                {
                    ListItem item = combo.Items[i];
                    arrItems.Add(item);
                }
                arrItems.Sort(comparer);
                combo.Items.Clear();
                for (i = 0; i < arrItems.Count; i++)
                {
                    combo.Items.Add((ListItem) arrItems[i]);
                }
            }
        }

        private class ComboTextComparer : IComparer
        {
            private int _modifier;

            public ComboTextComparer()
            {
                this._modifier = 1;
            }

            public ComboTextComparer(SortOrder order)
            {
                this._modifier = (int) order;
            }

            public int Compare(object o1, object o2)
            {
                ListItem cb1 = (ListItem) o1;
                ListItem cb2 = (ListItem) o2;
                return (cb1.Text.CompareTo(cb2.Text) * this._modifier);
            }

            public enum SortOrder
            {
                Ascending = 1,
                Descending = -1
            }
        }

        private class ComboValueComparer : IComparer
        {
            private int _modifier;

            public ComboValueComparer()
            {
                this._modifier = 1;
            }

            public ComboValueComparer(SortOrder order)
            {
                this._modifier = (int) order;
            }

            public int Compare(object o1, object o2)
            {
                ListItem cb1 = (ListItem) o1;
                ListItem cb2 = (ListItem) o2;
                return (cb1.Value.CompareTo(cb2.Value) * this._modifier);
            }

            public enum SortOrder
            {
                Ascending = 1,
                Descending = -1
            }
        }
    }
}

